import { useMutation } from "@apollo/react-hooks";
import gql from "graphql-tag";
import { Modal } from "antd";

import useAuth from "./useAuth";
import { handleErrors } from "../utils/handleErrors";
import { useRouter } from "./useRouter";

const LOGOUT = gql`
  mutation Logout {
    logout {
      user {
        id
        username
      }
      authorities {
        id
        name
      }
    }
  }
`;

const useLogout = () => {
  const { setLoginUser } = useAuth();
  const { push } = useRouter();

  const [logout] = useMutation(LOGOUT, {
    onError: ({ graphQLErrors, networkError }) => {
      handleErrors({ graphQLErrors, networkError });
    }
  });

  const handleLogout = () => {
    logout();
    Modal.destroyAll();
    setLoginUser(false);
    push("/login");
  };

  return {
    handleLogout
  };
};

export default useLogout;
